package com.bdqn.web;

import com.bdqn.pojo.News;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.NewsService;
import com.bdqn.service.SysUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Thymeleaf页面测试控制器
 *
 * @author LILIBO
 * @since 2024-09-19
 */
@Controller
public class DemoController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private NewsService newsService;

    /**
     * 欢迎页面
     *
     * @return
     */
    @GetMapping("/hello/{id}")
    public String hello(Model model, HttpSession session, @PathVariable("id") String id) {
        SysUser user = sysUserService.getById(id);
        model.addAttribute("user", user);
        model.addAttribute("test", "model");
        model.addAttribute("sex", "woman");
        model.addAttribute("flag", "yes");
        session.setAttribute("test", "session");
        return "demo/hello";
    }

    /**
     * 欢迎页面
     *
     * @return
     */
    @GetMapping("/index")
    public String index(Model model) {
        return "demo/index";
    }

    /**
     * 欢迎页面
     *
     * @return
     */
    @GetMapping("/user")
    public String user(Model model) {
        List<SysUser> users = sysUserService.list();
        model.addAttribute("users", users);
        return "demo/user";
    }

    @ResponseBody
    @PostMapping("/news")
    public Object addNews(@RequestBody News news) {
        // 调用接口时不带ID，会自动生成ID
        boolean save = newsService.save(news);
        System.out.println("保存" + (save ? "成功" : "失败"));
        // 使用了MyBatis-Plus，可以拿到ID
        return newsService.getById(news.getId());
    }

    @GetMapping("/loginx")
    public String toLoginx() {
        System.out.println("跳转到登录页面");
        return "security/login";
    }

    @PostMapping("/loginx")
    public String doLoginx() {
        System.out.println("执行登录方法");
        return "security/main";
    }

}
